import {Component, OnInit, TemplateRef} from "@angular/core";
import {LocalDataSource} from "ng2-smart-table";
import {SmartTableData} from "../../@core/data/smart-table";
import {ActivatedRoute} from "@angular/router";
import {NbDateService, NbDialogRef, NbDialogService} from "@nebular/theme";
import {AdminService} from "../../AdminService";
import {BaseRequest} from "../../utils/BaseRequest";
import {map} from "rxjs/operators";
import {StrUtils} from "../../utils/StrUtils";
import {BillExtaService} from "../../energy/api/api/billExta.service";
import {ResponseECARate} from "../../energy/api/model/responseECARate";
import {NgbTimepickerConfig, NgbTimeStruct} from '@ng-bootstrap/ng-bootstrap';
import {CustomTimeRender} from "../../utils/CustomTimeRender";

@Component({
  templateUrl: './cost-list.component.html',
  styles: [
      `
          nb-card {
              transform: translate3d(0, 0, 0);
          }

          .margin {
              margin: 10px;
          }
    `
  ]
})
export class CostListComponent {
  settings = {
    pager: {
      display: true,
      perPage: 20,
    },
    hideSubHeader: true,
    actions: {
      add: false,
      edit: false,
      columnTitle: '操作',
      position: 'right',
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      name: {
        title: '名称',
        type: 'string',
      },
      startTime: {
        title: '起始时间',
        type: 'custom',
        renderComponent: CustomTimeRender
      },
      endTime: {
        title: '结束时间',
        type: 'custom',
        renderComponent: CustomTimeRender
      },
      rate: {
        title: '费率',
        type: 'string',
      },
      extInfo: {
        title: '备注',
        type: 'string',
      },
    },
  };
  costName: string = null;
  source: DataDataSource;
  item: string;
  constructor(private service: SmartTableData
    , private dialogService: NbDialogService
    , private api: BillExtaService
    , private route: ActivatedRoute
    , private dateService: NbDateService<Date>
    , private admin: AdminService) {
    this.source = new DataDataSource(this.api, this.costName);
  }

  filter() {
    if (StrUtils.hasValue(this.costName))
      this.source.costName = this.costName;
    this.source.setPage(1);
  }

  openAddPrompt(dialog: TemplateRef<any>) {
    this.dialogService.open(dialog)
      .onClose.subscribe(v => {
      if (v == null) return;
      this.api.postECARate(new BaseRequest(
        [
          {
            name: v['costName'] + '(' + v['type'] + ')',
            startTime: v['startTime'],
            endTime: v['endTime'],
            rate: Number(v['rate']),
            extInfo: v['extInfo'],
          }
        ]
      )).toPromise().then(response => {
        console.log(response);
        this.source.refresh();
      })
    });
  }

  onDeleteConfirm(event): void {
    if (window.confirm('Are you sure you want to delete?')) {
      this.api.postECARate(new BaseRequest([
        {
          id:event.data['id']
        }
      ])).toPromise().then(res => {
        if (res.success) {
          event.confirm.resolve();
        } else {
          event.confirm.reject();
        }
      }).catch(e => {
        event.confirm.reject();
      });
      event.confirm.resolve();
    } else {
      event.confirm.reject();
    }
  }
}

export class DataDataSource extends LocalDataSource {
  all: number = -1;

  constructor(private api: BillExtaService, public costName?: string,public unitId?:number) {
    super()
  }

  count(): number {
    return this.all;
  }

  getElements(): Promise<any> {
    // return null;
    const query = {
      pageIndex: (this.pagingConf['page'] - 1) * this.pagingConf['perPage'],
      pageSize: this.pagingConf['perPage'],
      name: this.costName,
      unitId: this.unitId
    };
    return this.api.requestECARate(new BaseRequest(query)).pipe(map((res: ResponseECARate) => {
      this.all = res.dataCount;
      return res.data;
    })).toPromise();
  }
}
